<template>
  <div>
    <el-container>
      <el-main style="margin-left:-12px;font-weight: bolder;">{{id? '编辑分类':'新建分类'}}</el-main>
    </el-container>

    <!-- native指向原生表单  -->
    <el-form label-width="80px" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <el-select   required v-model="model.parent" placeholder="name">
          <el-option v-for=" item in parents" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input style="width: 280px;"  prefix-icon="el-icon-user" clearable maxlength = "20"  error required v-model="model.name" placeholder="name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="el-button--medium"  type="primary" native-type="submit" :plain="true">保存</el-button>
        <el-button type="danger" size="medium" native-type="button" @click="cancel" v-show="this.id" :plain="true">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {},
      parents: []
    };
  },
  created() {
    this.fetchParents();
    this.id && this.fetch();
  },
  methods: {
    async save() {
      //实现新增的保存和编辑的保存
      if (this.id) {
        const response = await this.$http.put(`rest/categories/${this.id}`,this.model);
      } else {
        const response = await this.$http.post("rest/categories", this.model);
      }
      this.$router.push("/categories/list");
      
      this.$message({
        type: "success",
        message: "保存成功",
        duration: 2000
      });
    },
    async fetch() {
      const response = await this.$http.get(`rest/categories/${this.id}`);
      this.model = response.data;
    },
    async fetchParents() {
      const response = await this.$http.get(`rest/categories`);
      this.parents = response.data;
    },
    //取消保存返回上一页
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped>
.el-button--medium{
    padding: 15px 60px!important;
}
</style>